<template>
  <div class="container">
    <div class="app-container">

      <el-tree default-expand-all :data="depts" :props="defaultProps">
        <template #default="{ data }">
          <el-row style="width: 100%;">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="12">{{ data.managerName }}</el-col>
                <el-col :span="12">
                  <el-dropdown @command="handleCommand($event,data.id)">
                    <span>
                      操作<i class="el-icon-arrow-down" />
                    </span>
                    <template>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="add">添加</el-dropdown-item>
                        <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                        <el-dropdown-item command="del">删除</el-dropdown-item>

                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <el-dialog :visible.sync="showAddDept" :title="title" @close="handleClose">
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入" style="width:80%" size="mini" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="addForm.code" placeholder="请输入" style="width:80%" size="mini" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <el-select v-model="addForm.managerId" placeholder="请输入">
              <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="addForm.introduce" placeholder="请输入" style="width:80%" size="mini" />
          </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center;">
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button>取消</el-button>
        </div>
      </el-dialog></div>

  </div>
</template>
<script>
import { getDepartment, getManagerList, addDepartments, getDepartDetail, editDepartment, deleteDepartment } from '@/api/department'
import { transList2TreeData } from '@/utils'
export default {
  name: 'Department',
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showAddDept: false,
      addForm: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      },
      rules: {
        name: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        },
        { validator: (rule, value, callback) => {
          let temp = this.list
          if (this.addForm.id) {
            temp = temp.filter(item => item.id !== this.addForm.id)
          }
          if (temp.some(item => item.name === value)) {
            callback(new Error('和已有部门的名字重复'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
        }
        ],

        code: [{
          required: true,
          message: '请输入部门编号',
          trigger: 'blur'
        },
        { validator: (rule, value, callback) => {
          if (this.list.some(item => item.name === value)) {
            callback(new Error('部门编号已存在'))
          } else {
            callback()
          }
        }, trigger: 'blur' }],
        managerId: [{
          required: true,
          message: '请选择部门负责人',
          trigger: 'change'
        }],
        introduce: [{
          required: true,
          message: '请输入部门介绍',
          trigger: 'blur'
        }]
      },
      managerList: [],
      list: [], // 备份的数据 用户查询是否重复
      parentId: ''// 用于添加子部门携带的id
    }
  },
  computed: {
    title() {
      return this.addForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getDepartment()
    this.getManagerList()
  },

  methods: {
    // 获取部门列表
    async getDepartment() {
      const res = await getDepartment()
      this.list = res// 单独备份一个数据用于查询是否重复
      this.depts = transList2TreeData(res, 0)// 处理树形数据
    },
    // 处理下拉框三个点击业务
    handleCommand(type, id) {
      if (type === 'add') {
        this.showAddDept = true
        this.parentId = id
      }
      if (type === 'edit') {
        this.showAddDept = true
        this.parentId = id
        this.getDepartDetail()
      }
      if (type === 'del') {
        // 删除
        // console.log(333)
        this.parentId = id
        // this.deleteDepartment()
        // 这里是二次确认
        this.$confirm('此操作将永久删除该部门, 是否继续?', '警告', {
          cancelButtonText: '我想想', // 配置取消按钮文字
          type: 'warning'// 配置图标
        }).then(() => {
          this.deleteDepartment()
        }).catch(() => {
          console.log('取消')
        })
      }
    },
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
      this.getDepartment()
      this.$message.success('删除成功')
    },
    // 获取管理员信息
    getManagerList() {
      getManagerList().then(res => {
        this.managerList = res
      })
    },
    // 数据回显
    async  getDepartDetail() {
      const res = await getDepartDetail(this.parentId)
      this.addForm = res
    },
    // 清空数据
    handleClose() {
      this.$refs.addForm.resetFields()
      this.addForm = {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      }
    },
    submit() {
      this.$refs.addForm.validate(async(isOK) => {
        if (isOK) {
          if (this.addForm.id) {
            await editDepartment(this.addForm)
            this.$message.success('修改成功')
          } else {
            await addDepartments({
              ...this.addForm,
              pid: this.parentId
            })
            this.$message.success('添加成功')
          }

          this.getDepartment()
          this.showAddDept = false
          // this.$refs.addForm.resetFields()
          this.handleClose()
        }
      })
    }

  }
}
</script>
